import mAppInfo from '../appInfo'

function NetTool() {
	this.appInfo=mAppInfo
	//数据请求
	this._getAjaxUrlValueBackground = function(url, data, fn, isBackground,failCallback) {
		var that = this;
		// 加载model
		if (!isBackground) {
			// uni.showLoading({
			// 	title: '加载中...',
			// })
		}
		let token = uni.getStorageSync("token")
		// 添加版本控制 
		var arrData = {
			version: '1.0.0.1',
			business_id: this.appInfo.business_id,
			shop_id: uni.getStorageSync('shop_id') ? uni.getStorageSync('shop_id') : this.appInfo.shop_id,
			// user_id: uni.getStorageSync('user_id'),
			config_business_id:this.appInfo.config_business_id,
			...data,
			token: token
		}

		
		if (data.user_id == '' || data.user_id == "") {
			delete arrData.user_id;
		}
		if (data.shop_id == '' || data.shop_id == "") {
			delete arrData.shop_id;
		}

		uni.request({
			url: this.appInfo.apiUrl + url,
			data: arrData,
			method: "GET",
			success: function(res) {
				uni.hideLoading();
				// typeof fn == "function" && fn(res);
				if (res.data.success) {
					if (res.data.data) {
						typeof fn == "function" && fn(res.data.data);
					} else if (res.data) {
						typeof fn == "function" && fn(res.data);
					} else {
						typeof fn == "function" && fn(res);
					}
				} else {
					if(res.data.code == 10000){
						uni.removeStorageSync("token");
						uni.removeStorageSync("user_id");
						uni.removeStorageSync("userInfo");
						return;
					}else{
						if(failCallback){
							typeof failCallback == "function" && failCallback(res.data);
							return;
						}
					}
					
					if (res.data && res.data.token) {
						typeof fn == "function" && fn(res.data);
						return;
					}
					if (res.data.msg && res.data.msg != '') {
						uni.showToast({
							title: res.data.msg,
							icon: "none",
							duration: 3000,
						})
					}
				}
			},
			fail: function(XMLHttpRequest) {
				uni.hideLoading();
				uni.showToast({
					title: "网络连接超时",
					icon: 'success',
					image: "/images/info.png",
					duration: 2000
				})
			},
			complete: function(res) {
				// uni.hideLoading();
			}
		});
	};


	this.getAjaxUrlValue = function(url, data, fn,fail) {
		this._getAjaxUrlValueBackground(url, data, fn,false,fail)
	};
	
	this.getAjax = function(url, data, fn,fail) {
		 
		this._getAjaxUrlValueBackground(url, data, fn,false,fail)
	};
	this.getAjaxUrlValueBackground = function(url, data, fn,fail) {
		this._getAjaxUrlValueBackground(url, data, fn, true,fail)
	};
	
}

module.exports = new NetTool();
